import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/admin',
      name: 'admin',
      component: () => import('../views/admin/Layout.vue'),
      meta: { requiresAuth: true },
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          component: () => import('../views/admin/Dashboard.vue')
        },
        {
          path: 'links',
          name: 'links',
          component: () => import('../views/admin/Links.vue')
        },
        {
          path: 'applicants',
          name: 'applicants',
          component: () => import('../views/admin/Applicants.vue')
        }
      ]
    },
    {
      path: '/apply/:token',
      name: 'apply',
      component: () => import('../views/applicant/Form.vue')
    },
    {
      path: '/success',
      name: 'success',
      component: () => import('../views/applicant/Success.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFound.vue')
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果要访问需要认证的页面但没有token，重定向到登录页
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } 
  // 如果已有token且访问的是首页或登录页，直接跳转到仪表盘
  else if (token && (to.name === 'home' || to.name === 'login')) {
    next('/admin/dashboard')
  }
  // 其他情况正常放行
  else {
    next()
  }
})

export default router 